<template>
  <Container class="manage-edit">
    <div v-if="isEdit || Object.keys(secondData).length" slot="header" class="container-header title title-center">
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="$router.back()">返回</Button>
      <span class="mid">{{ isEdit ? '编辑商品申请' : '新增商品申请' }}</span>
      <div class="fr">
        <span class="big">{{ secondData.fristName }}</span>
        <span v-if="secondData.secondName" class="arrow">></span>
        <span v-if="secondData.secondName" class="big">{{ secondData.secondName }}</span>
        <span v-if="secondData.thirdName" class="arrow">></span>
        <span v-if="secondData.thirdName" class="big">{{ secondData.thirdName }}</span>
        <Button class="ml" @click="changeCategory">切换</Button>
      </div>
    </div>
    <div v-if="isLook" slot="header" class="container-header title title-center">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="$router.back()">返回</Button>
    </div>
    <div v-if="!isLook && !isEdit && Object.keys(secondData).length === 0" slot="header" class="container-header title title-center">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <!-- 商品管理新增 -->
    <div v-if="!productId && Object.keys(secondData).length === 0" slot="header" class="container-header mb">
      <Form class="search">
        <Row>
          <i-col span="6">
            <FormItem label="类目">
              <CategorySelect v-model="form.categoryId" />
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem label="商品品牌" placeholder="商品品牌">
              <BrandSelect v-model="form.brandId" />
            </FormItem>
          </i-col>
          <i-col span="11">
            <FormItem label="选择商品">
              <Select
                ref="goodsDetail"
                v-model="form.productId"
                :remote-method="remote"
                filterable
                remote
                label-in-value
                :loading="loadingDetail"
                clearable
                @on-change="onSelectProduct"
                @on-clear="clear"
                @on-open-change="onOpenProduct"
              >
                <Option v-for="(item, index) in productList" :key="index" :value="item.id">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <p v-if="productNum > 0" class="font-red big tips">提示：该商品已存在，不能继续创建保存多份商品</p>
    </div>
    <Tabs v-model="tab" :animated="false">
      <TabPane name="tab1" label="商品信息" class="scroll">
        <!-- 商品基本信息 -->
        <BaseEditItem
          ref="baseEdit"
          :product-type="productType"
          :brand-d-t-o-list="brandDTOList"
          :product-id="productId"
          :is-look="isLook"
          :flag="flag"
          :category-list="categoryList"
          :is-product="isProduct"
          @onBrandFigure="onBrandFigure"
        />
        <!-- 商品属性 -->
        <NatureEditItem
          v-show="productAttributeDTOs.length > 0"
          ref="natureEdit"
          :product-type="productType"
          :is-product="isProduct"
          :tire-ratio-arr="tire_ratioArr"
          :tire-size-arr="tire_sizeArr"
          :tire-width-arr="tire_widthArr"
          :is-look="isLook"
          @changeFigureData="changeFigureData"
        />
        <GoodsLogistics ref="freightEdit" />
        <!-- 商品图片 -->
        <PicEditItem ref="picEdit" :is-look="isLook" />
        <!-- 销售属性 -->
        <SaleNatureEditItem v-if="productType === 'NORMAL'" ref="saleEdit" :center-product-sku-arr="centerProductSkuArr" :is-image="isImage" :flag="flag" :product-id="productId" :is-look="isLook" :sale-attrs="saleAttrs" />
        <!-- 商品标签 -->
        <TagEditItem v-if="isProduct" ref="tagEdit" :is-look="isLook" />
        <!-- 服务标签 -->
        <ServiceEditItem v-if="isProduct" ref="serverEdit" :is-look="isLook" />
      </TabPane>
      <TabPane name="tab2" label="图文信息" class="scroll">
        <!-- 商品描述 -->
        <DescriptionEditItem ref="decEdit" :is-look="isLook" />
      </TabPane>
    </Tabs>
    <div v-if="!isLook" slot="footer" class="container-footer bg-white">
      <Button v-if="isProduct" type="primary" class="mr" :disabled="btnDisable" size="large" @click="onSave">保存</Button>
      <Button v-else type="primary" class="mr" :disabled="btnDisable" size="large" @click="onSave">提交申请</Button>
    </div>
    <Loader v-if="productId" :status="status" @refresh="getInfo(productId)" />
    <Loader v-if="!productId" :status="status" @refresh="getDetailData(form.title)" />
  </Container>
</template>

<script>
import { preFixPath, getTireArr } from '@/util'
import CategorySelect from '@/components/CategorySelect'
import BrandSelect from '@/components/BrandSelect'
import BaseEditItem from './edit/BaseEditItem'
import NatureEditItem from './edit/NatureEditItem'
import PicEditItem from './edit/PicEditItem'
import SaleNatureEditItem from './edit/SaleNatureEditItem'
import DescriptionEditItem from './edit/DescriptionEditItem'
import TagEditItem from './edit/TagEditItem'
import ServiceEditItem from './edit/ServiceEditItem'
import GoodsLogistics from './edit/GoodsLogistics'
export default {
  components: {
    BaseEditItem,
    NatureEditItem,
    PicEditItem,
    SaleNatureEditItem,
    DescriptionEditItem,
    TagEditItem,
    ServiceEditItem,
    CategorySelect,
    BrandSelect,
    GoodsLogistics
  },
  data () {
    return {
      preFixPath,
      flag: this.$route.query.flag,
      productList: [],
      form: {
        categoryId: '',
        brandId: '',
        productId: '',
        title: ''
      },
      loadingDetail: false,
      tab: 'tab1',
      productId: null, //商品的id（从编辑那边传过来）
      btnDisable: false,
      categoryName: '', //分类的名称
      status: 'pass',
      brandDTOList: [], //商品品牌
      productType: 'NORMAL', //商品类型
      productAttributeDTOs: [], //商品属性
      productSaleDTOs: [], //销售属性
      saleAttrs: {}, //传递给子组件的销售属性
      isImage: false, //销售属性里是否要上传图片
      saleSkuIdArr: [], //编辑时后台传过来的销售属性的id集合
      saleImgIdArr: [], //编辑时后台传过来的销售属性的图片id集合
      productNum: 0, //是否重复创建的商品
      categoryId: null, //分类id
      centerProductId: null, // 商品中心id
      title: '商品新增',
      isHasAdd: false,
      tire_ratioArr: [],
      tire_sizeArr: [],
      tire_widthArr: [],
      secondData: {}, // 新增申请商品时，从前一个页面带过来的参数
      isLook: false, // 是否从申请页面的查看按钮过来
      isEdit: false, // 是否从申请页面的编辑按钮过来
      categoryList: [], // 店铺分类
      meunData: [],
      productAuditDTO: {}, // 申请商品需要带的参数
      isProduct: true, // 是否是商品管理
      skuMainImgIdArr: [], // 编辑时后台传过来的sku主图的id集合
      productSkuImagesDTOs: [], // 从后台传过来的sku主图的数据
      centerProductSkuArr: []
    }
  },
  mounted () {
    // if (this.isProduct) this.getShopData() // 获取店铺分类
    if (this.$route.query.productId) {
      this.productId = this.$route.query.productId
      this.title = '商品编辑'
      if (this.$route.query.from === 'look') {
        this.isLook = true
        this.title = '查看申请商品'
        this.isProduct = false
        if (window.sessionStorage.getItem('productAuditDTO')) window.sessionStorage.removeItem('productAuditDTO')
      }
      if (this.$route.query.from === 'edit') {
        this.isProduct = false
        this.isEdit = true
        this.title = '编辑申请商品'
        if (this.$route.query.productAuditDTO) { // 只有从申请商品的编辑按钮 才本地缓存productAuditDTO
          this.productAuditDTO = JSON.parse(this.$route.query.productAuditDTO)
          window.sessionStorage.setItem('productAuditDTO', JSON.stringify(this.productAuditDTO))
        }
      }
      this.getInfo(this.productId)
    } else if (this.$route.query.toEditData) {
      this.isProduct = false
      this.secondData = JSON.parse(this.$route.query.toEditData)
      this.getBaseData()
    } else {
      this.isProduct = true
      this.getDetailData()
    }
    if (this.$route.query.from === 'add') {
      if (window.sessionStorage.getItem('productAuditDTO')) window.sessionStorage.removeItem('productAuditDTO')
    }
  },
  beforeRouteLeave (to, from, next) {
    if (window.sessionStorage.getItem('productAuditDTO')) window.sessionStorage.removeItem('productAuditDTO')
    next()
  },
  methods: {
    getDetailData (query = '') {
      this.loadingDetail = true
      this.form.title = query
      let param = {
        keyword2: query,
        brandId: this.form.brandId,
        isShelf: true
      }
      if (this.form.categoryId) param.categoryId = this.form.categoryId
      this.$jsonPost('/product/business/center/page', param).then(data => {
        this.loadingDetail = false
        this.productList = (data.records || []).map(item => {
          return {
            id: item.id,
            label: item.title
          }
        })
      })
    },
    remote (query) {
      this.form.title = query
      this.oTimerDetail && clearTimeout(this.oTimerDetail)
      this.oTimerDetail = setTimeout(() => {
        this.getDetailData(query)
      }, 500)
    },
    clear () {
      this.remote('')
    },
    onOpenProduct (isOpen) {
      if (isOpen) this.getDetailData(this.form.title)
    },
    onSelectProduct (item) {
      this.isHasAdd = !!item
      if (!item) return
      this.btnDisable = true
      this.status = 'loading'
      this.form.title = item.label
      this.getNewInfo(item.value).then(data => {
        this.fillData(data, this.productNum)
      })
    },
    getNewInfo (id) {
      return this.$ajaxGet(`/product/business/center/f_${id}`).then(data => {
        this.centerProductId = id
        this.categoryId = data.productInfoDTO.categoryId
        this.productNum = data.productNum
        return data
      })
    },
    getInfo (id) {
      this.btnDisable = true
      this.status = 'loading'
      let url = (this.isLook || this.isEdit) ? '/product/apply/getFullDtoById/' : '/product/business/getFull/'
      this.$ajaxGet(`${url}${id}`).then(data => {
        this.categoryId = data.productInfoDTO.categoryId
        this.fillData(data)
      })
    },
    fillData (data, productNum = 0) {
      if (this.isEdit) {
        this.getMenuData().then(() => {
          let level = -1
          this.secondData.endId = this.categoryId
          this.meunData.forEach(item => {
            if (item.id === this.secondData.endId) {
              level = item.level
              if (level === 3) {
                this.thirdId = item.id
                this.secondData.thirdName = item.name
                this.secordId = item.pId
                this.meunData.forEach(m => {
                  if (m.id === this.secordId) {
                    this.secondData.secondName = m.name
                    this.fristId = m.pId
                    this.meunData.forEach(j => {
                      if (j.id === this.fristId) {
                        this.secondData.fristName = j.name
                      }
                    })
                  }
                })
              } else if (level === 2) {
                this.secondData.thirdName = null
                this.secondData.secondName = item.name
                this.secordId = item.id
                this.fristId = item.pId
                this.meunData.forEach(m => {
                  if (m.id === this.fristId) {
                    this.secondData.fristName = m.name
                  }
                })
              } else {
                this.fristId = item.id
                this.secondData.thirdName = null
                this.secondData.secondName = null
                this.secondData.fristName = item.name
              }
            }
          })
        })
      }
      this.getBaseData().then(async () => {
        this.btnDisable = productNum > 0
        this.status = 'pass'
        // 商品标签
        if (this.isProduct) { // 如果是商品管理，才有商品标签跟设置
          if (data.tagDTOs) {
            this.$refs.tagEdit.checkedArr = (data.tagDTOs || []).map(item => item.id)
            this.$refs.tagEdit.productTagDTOs = data.productTagDTOs
            this.$refs.tagEdit.backData = data.productTagDTOs
          }
          // 是否上架
          this.$refs.tagEdit.isShelf = data.productInfoDTO.isShelf
        }
        // 服务标签
        if (this.isProduct) { // 如果是商品管理，才有商品标签跟设置
          if (data.productServiceTagIds) {
            this.$refs.serverEdit.checkedArr = (data.productServiceTagIds || []).map(item => {
              return item
            })
          }
        }
        // 商品基本信息
        this.$refs.baseEdit.form.id = data.productInfoDTO.id
        this.$refs.baseEdit.form.brandId = data.productInfoDTO.brandId
        this.$refs.natureEdit.brandId = data.productInfoDTO.brandId // 品牌id要传到类目属性里去，花纹切换的时候需要品牌id去查找花纹模板详情
        this.$refs.baseEdit.form.code = data.productInfoDTO.code
        this.$refs.baseEdit.form.title = data.productInfoDTO.title
        this.$refs.baseEdit.form.brandName = data.productInfoDTO.brandName
        this.$refs.baseEdit.form.taxRate = data.productInfoDTO.taxRate
        this.$refs.baseEdit.form.unit = data.productInfoDTO.unit
        this.$refs.baseEdit.form.weight = data.productInfoDTO.weight
        this.$refs.baseEdit.form.subTitle = data.productInfoDTO.subTitle
        this.$refs.baseEdit.form.subTitleHint = data.productInfoDTO.subTitleHint
        this.$refs.baseEdit.form.subTitleLink = data.productInfoDTO.subTitleLink
        this.$refs.baseEdit.form.ownerCategoryId = data.productInfoDTO.ownerCategoryId === '0' ? null : data.productInfoDTO.ownerCategoryId // 店铺分类id
        this.$refs.baseEdit.form.primaryNum = data.productInfoExtDTO.primaryNum || 1
        this.$refs.baseEdit.form.orderNum = data.productInfoExtDTO.orderNum || 1
        if (this.productType !== 'NORMAL') {
          this.$refs.baseEdit.form.skuId = data.productSkuDTOs[0].id
          this.$refs.baseEdit.form.salePrice = data.productSkuDTOs[0].salePrice
          this.$refs.baseEdit.form.barcode = data.productSkuDTOs[0].barcode
          this.$refs.baseEdit.form.invoicePrice = data.productSkuDTOs[0].invoicePrice
          this.$refs.baseEdit.form.marketPrice = data.productSkuDTOs[0].marketPrice
          this.$refs.baseEdit.form.stock = data.productSkuDTOs[0].stock
        }
        // 物流信息
        this.$refs.freightEdit.freightTemplateId = data.productInfoExtDTO.freightTemplateId
        //商品图片
        this.$refs.picEdit.uploadList = data.productInfoImagesDTOs.map(item => {
          return {
            sort: item.sort,
            imgUrl: item.resource,
            status: 'finished',
            id: item.id
          }
        })
        this.$refs.picEdit.idsArr = data.productInfoImagesDTOs.map(item => item.id)
        //商品描述
        let editorContent = data.productInfoExtDTO.description
        // let editorUrl = 'http://zc-peppa-dev.oss-cn-hangzhou.aliyuncs.com';
        // let editorUrl = this.preFixPath
        // this.$refs.decEdit.tinymceHtml = editorContent.replace(/src="\//g, 'src="' + editorUrl + '/')//有可能图片的链接地址是外网的
        this.$refs.decEdit.tinymceHtml = editorContent
        this.$refs.decEdit.id = data.productInfoExtDTO.id
        // this.$refs.decEdit.toBackContent = editorContent;
        //this.$refs.decEdit.editor.content = editorContent.replace(/src="\//g,'src="'+editorUrl+'/');//有可能图片的链接地址是外网的
        //类目属性
        if (data.productAttributeDTOs && data.productAttributeDTOs.length > 0) {
          // this.$refs.natureEdit.allAttributeArr = data.productAttributeDTOs
          if (this.productAttributeDTOs.length) this.$refs.natureEdit.editData(data.productAttributeDTOs)
        } else { // 防止切换的时候，上一个商品的信息残留
          if (this.productAttributeDTOs.length) this.$refs.natureEdit.allAttributeArr = []
        }
        // 类目属性（轮胎属性）
        if (data.productInfoTireExtDTO && this.productType !== 'NORMAL') {
          this.$refs.natureEdit.productInfoTireExtDTO = data.productInfoTireExtDTO
          this.productAttributeDTOs.forEach((j, v) => {
            switch (j.name) {
              case '扁平率':
                // this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireAspectRatio)
                this.$refs.natureEdit.productInfoTireExtDTO.tireAspectRatio = data.productInfoTireExtDTO.tireAspectRatio
                break
              case '花纹':
                this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireFigure)
                break
              case '层级':
                this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireLayer)
                break
              case '负荷指数':
                this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireLoad)
                break
              case '直径':
                // this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireRim)
                this.$refs.natureEdit.productInfoTireExtDTO.tireRim = data.productInfoTireExtDTO.tireRim
                break
              case '胎面宽':
                // this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireWidth)
                this.$refs.natureEdit.productInfoTireExtDTO.tireWidth = data.productInfoTireExtDTO.tireWidth
                break
              case '速度级别':
                this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireSpeed)
                break
              case '规格':
                this.$set(this.productAttributeDTOs[v], 'value', data.productInfoTireExtDTO.tireSpec)
                break
              case '类型标识':
              // this.$set(this.productAttributeDTOs[v], 'value', data.productInfoTireExtDTO.tireTypeSymbol)
              // 类型标识从输入框改成了下拉框
                this.$set(this.productAttributeDTOs[v], 'attributeValueId', data.productInfoTireExtDTO.tireTypeSymbol)
                break
            }
          })
        }
        //销售属性
        if (this.productType === 'NORMAL') {
          let productSkuDTOs = data.productSkuDTOs
          //编辑的时候判断销售属性有没有改变过，如果改变了，那serverData=[]
          let saleChangeFlag = false // 销售属性是否改变
          let attrIdArrs = []
          let valIdArrs = []

          this.productSaleDTOs.forEach(item => {
            attrIdArrs.push(item.id)
            item.attributeValueDTOList.forEach(m => {
              valIdArrs.push(m.id)
            })
          })
          productSkuDTOs.forEach(item => {
            let productSkuAttrDTOs = item.productSkuAttrDTOs || []
            productSkuAttrDTOs.forEach(m => {
              let attrId = m.attributeNameId
              let valId = m.attributeValueId
              if (attrIdArrs.indexOf(attrId) < 0) {
                saleChangeFlag = true
              }
              if (valIdArrs.indexOf(valId) < 0) {
                saleChangeFlag = true
              }
            })
          })
          let productSkuArr = this.handleSkuDTO(data)
          if (data.productInfoDTO.centerProductId) {
            const centerProductData = await this.getNewInfo(data.productInfoDTO.centerProductId)
            this.centerProductSkuArr = this.handleSkuDTO(centerProductData, 1)
          } else {
            this.centerProductSkuArr = productSkuArr
          }
          if (!saleChangeFlag) {
            this.$refs.saleEdit.serverData = productSkuArr
            this.$refs.saleEdit.setInfoSale()
          } else {
            this.$refs.saleEdit.serverData = []
          }
        }
      })
    },
    handleSkuDTO (data, type) {
      let productSkuArr = []
      let productSkuDTOs = data.productSkuDTOs
      productSkuDTOs.forEach(item => {
        if (type !== 1) this.saleSkuIdArr.push(item.id)
        let target = {}
        target.proCode = item.barcode
        target.invoice = item.invoicePrice
        target.marketPrice = item.marketPrice
        target.sale = item.salePrice
        target.stock = item.stock
        target.id = item.id
        target.code = item.code
        // 线上修改撤回
        /* sku主图start */
        this.productSkuImagesDTOs = item.productSkuImagesDTOs || [] // 主图的图片数组
        this.productSkuImagesDTOs.forEach(p => {
          target.skuImgArr = [{ imgUrl: p.resource, status: 'finished' }]
          if (type !== 1) this.skuMainImgIdArr.push(p.id) // 把主图的id都集合在一个数组里
        })

        /* sku主图end */
        let productSkuAttrDTOs = item.productSkuAttrDTOs || []
        if (productSkuAttrDTOs.length === 2) {
          productSkuAttrDTOs.forEach((m, i) => {
            if (i === 0) {
              target.hwParentId = m.attributeNameId
              target.hwParentName = m.attributeName
              target.hw = m.attributeValueId
              target.hwName = m.attributeValue
            } else if (i === 1) {
              target.gzParentId = m.attributeNameId
              target.gzParentName = m.attributeName
              target.gz = m.attributeValueId
              target.gzName = m.attributeValue
            }
          })
        } else if (productSkuAttrDTOs.length === 1) {
          let hwName = this.saleAttrs.hw ? this.saleAttrs.hw.label : ''
          let gzName = this.saleAttrs.gz ? this.saleAttrs.gz.label : ''
          productSkuAttrDTOs.forEach((m, i) => {
            if (m.attributeName === hwName) {
              target.hwParentId = m.attributeNameId
              target.hwParentName = m.attributeName
              target.hw = m.attributeValueId
              target.hwName = m.attributeValue
            } else if (m.attributeName === gzName) {
              target.gzParentId = m.attributeNameId
              target.gzParentName = m.attributeName
              target.gz = m.attributeValueId
              target.gzName = m.attributeValue
            }
          })
        }
        productSkuArr.push(target)
      })
      if (data.productSkuAttrImagesDTOs.length > 0) {
        data.productSkuAttrImagesDTOs.forEach(item => {
          if (type !== 1) this.saleImgIdArr.push(item.id)
          productSkuArr.forEach(m => {
            if (m.hw) {
              if (m.hw == item.skuAttrValueId) {
                m.img = item.image
                m.uploadList = []
                m.uploadList.push({ imgUrl: m.img })
                m.imgId = item.id
              }
            } else { //只有规则
              if (m.gz == item.skuAttrValueId) {
                m.img = item.image
                m.uploadList = []
                m.uploadList.push({ imgUrl: m.img })
                m.imgId = item.id
              }
            }
          })
        })
      }
      return productSkuArr
    },
    async getBaseData () {
      let endId = Object.keys(this.secondData).length ? this.secondData.endId : this.categoryId
      await this.$ajaxGet(`/product/common/detail/${endId}`).then(data => {
        this.productAttributeDTOs = []
        this.productSaleDTOs = []
        let arr = []
        this.brandDTOList = (data.brandDTOList || []).map(item => { //品牌
          return {
            id: item.id,
            name: item.name
          }
        })
        this.productType = data.categoryDTO.productType //商品类型
        this.categoryName = data.categoryDTO.name
        if (this.productType !== 'NORMAL') this.getTireData()
        if (this.productType !== 'NORMAL') { // 轮胎
          data.tireAttrList.forEach(item => {
            if (item.name !== '扁平率' && item.name !== '直径' && item.name !== '胎面宽') {
              let target = {
                name: item.name,
                isMust: item.must,
                editType: item.editType,
                type: 'tire'
              }
              target.attributeValueDTOList = (item.productDictionaryDTOList || []).map(m => {
                return {
                  value: m.dataValue,
                  attributeValueId: m.dataValue
                }
              })
              arr.push(target)
            }
          })
        }
        let attrNameDTOList = data.attrNameDTOList
        attrNameDTOList.forEach(item => {
          if (item.attrNameDTO.type !== 'SALES_ATTRIBUTE') {
            let target = {
              name: item.attrNameDTO.name,
              attributeId: item.attrNameDTO.id,
              isImage: item.attrNameDTO.isImage,
              isMust: item.attrNameDTO.isMust,
              type: item.attrNameDTO.type,
              editType: item.attrNameDTO.editType,
              attributeValueDTOList: []
            }
            target.attributeValueDTOList = (item.attrValueDTOList || []).map(m => {
              return {
                value: m.value,
                attributeValueId: m.id
              }
            })
            this.productAttributeDTOs.push(target) //商品属性
          } else {
            let target = {
              name: item.attrNameDTO.name,
              id: item.attrNameDTO.id,
              isImage: item.attrNameDTO.isImage,
              attributeValueDTOList: []
            }
            target.attributeValueDTOList = (item.attrValueDTOList || []).map(m => {
              return {
                value: m.value,
                id: m.id
              }
            })
            this.productSaleDTOs.push(target) //销售属性
          }
        })
        if (arr.length) this.productAttributeDTOs = arr.concat(this.productAttributeDTOs)
        if (this.productAttributeDTOs.length) this.$refs.natureEdit.productAttributeDTOs = this.productAttributeDTOs
        this.productSaleDTOs.forEach((item, index) => {
          if (index === 0) {
            let hwObj = {}
            this.saleAttrs.hw = hwObj
            hwObj.label = item.name
            hwObj.id = item.id
            hwObj.isImage = item.isImage
            hwObj.checkbox = []
            let attributeValueDTOList = item.attributeValueDTOList
            hwObj.checkbox = attributeValueDTOList.map(m => {
              return {
                id: m.id,
                value: m.value
              }
            })
          } else if (index === 1) {
            let gzObj = {}
            this.saleAttrs.gz = gzObj
            gzObj.isImage = item.isImage
            gzObj.label = item.name
            gzObj.id = item.id
            gzObj.checkbox = []
            let attributeValueDTOList = item.attributeValueDTOList
            gzObj.checkbox = attributeValueDTOList.map(m => {
              return {
                id: m.id,
                value: m.value
              }
            })
          }
        })
        if (this.productType === 'NORMAL') this.$refs.saleEdit.getSaleAttrs(this.saleAttrs)
      }).catch(() => {
      })
    },
    getShopData () { // 店铺分类
      this.$ajaxGet('/product/supplier_category/tree').then(data => {
        this.categoryList = (data || []).map(parent => {
          let parentTarget = {
            id: parent.categoryDTO.id,
            label: parent.categoryDTO.name
          }
          if (parent.childCategoryList.length) {
            let childList = parent.childCategoryList.map(child => {
              let childTarget = {
                id: child.categoryDTO.id,
                label: child.categoryDTO.name
              }
              if (child.childCategoryList.length) {
                let grandsonList = child.childCategoryList.map(grandson => {
                  let grandsonTarget = {
                    id: grandson.categoryDTO.id,
                    label: grandson.categoryDTO.name
                  }
                  return grandsonTarget
                })
                childTarget.children = grandsonList
              }
              return childTarget
            })
            parentTarget.children = childList
          }
          return parentTarget
        })
      })
    },
    jumpPrevPage () {
      this.$router.push({
        name: 'product/manage/list',
        query: {
          currentPage: this.$route.query.currentPage,
          pageSize: this.$route.query.pageSize
        }
      })
    },
    async getMenuData () {
      await this.$ajaxGet('/product/common/supplier_tree', { isEnabled: true }).then(data => {
        this.meunData = this.renderArr(data)
      })
    },
    renderArr (d) {
      let arr = []
      let render = function (data) {
        data.forEach(item => {
          let target = {}
          target.name = item.categoryDTO.name
          target.id = item.categoryDTO.id
          target.pId = item.categoryDTO.parentId
          target.level = item.categoryDTO.treePath.split(',').length - 3
          target.productType = item.categoryDTO.productType
          arr.push(target)
          if (item.childCategoryList.length > 0) render(item.childCategoryList)
        })
      }
      render(d)
      return arr
    },
    onSave () {
      if (this.btnDisable) return
      this.btnDisable = true
      if (!this.productId && !this.isHasAdd && this.isProduct) {
        this.btnDisable = false
        this.$Notice.error({
          title: '错误提醒',
          desc: '新增时，请先选择商品'
        })
        return
      }
      this.$refs.baseEdit.$refs.formValidate.validate((valid) => {
        if (valid) {
          let baseTireFlag = true
          if (this.productType !== 'NORMAL') {
            if ((!this.$refs.baseEdit.form.salePrice && this.$refs.baseEdit.form.salePrice != 0) || (!this.$refs.baseEdit.form.marketPrice && this.$refs.baseEdit.form.marketPrice != 0)) {
              baseTireFlag = false
            }
          }
          if (!baseTireFlag) {
            this.btnDisable = false
            this.$Notice.error({
              title: '错误提醒',
              desc: '请先完善商品基本信息必填项'
            })
            return
          }
          if (this.productAttributeDTOs.length > 0) {
            let requireProductAttrs = [] // 除了轮胎之外的必填属性
            this.productAttributeDTOs.forEach(item => {
              if (item.isMust) {
                if (item.isMust && item.type !== 'tire') requireProductAttrs.push(item)
              }
            })
            let alreadyProductAttrs = this.$refs.natureEdit.allAttributeArr
            let requireCount = 0
            alreadyProductAttrs.forEach(item => {
              requireProductAttrs.forEach(m => {
                if (item.attributeId === m.attributeId && item.value) {
                  requireCount++
                }
              })
            })
            let productInfoTireExtDTO = this.$refs.natureEdit.productInfoTireExtDTO
            let tireFlag = true
            if (this.productType !== 'NORMAL') {
              if (!productInfoTireExtDTO['tireWidth']) tireFlag = false
              if (!productInfoTireExtDTO['tireRim']) tireFlag = false
              if (!productInfoTireExtDTO['tireFigure']) tireFlag = false
              if (!productInfoTireExtDTO['tireSpec']) tireFlag = false
            }
            if (requireCount < requireProductAttrs.length || !tireFlag) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '请先完善商品属性必填项'
              })
              return
            }
          }
          if (this.$refs.picEdit.uploadList.length < 1) { //商品图片一定上传5张
            this.btnDisable = false
            this.$Notice.error({
              title: '错误提醒',
              desc: '请至少上传1张图片'
            })
            return
          }

          if (this.productType === 'NORMAL') {
            let chData = this.$refs.saleEdit.tableData
            let isImage = this.$refs.saleEdit.isImage
            let imgFlag = false
            let marketFlag = false
            let saleFlag = false
            let codeFlag = false
            if (chData.length === 0) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '请选择销售属性'
              })
              return
            }
            let hasImageArr = []
            let notImageArr = []
            if (isImage) {
              hasImageArr = chData.filter(item => item.uploadList.length)
              notImageArr = chData.filter(item => !item.uploadList.length)
              notImageArr.forEach(m => {
                hasImageArr.forEach(n => {
                  if ((n.hw && n.gz) || (n.hw && !n.gz)) {
                    if (m.hw === n.hw) m.uploadList = n.uploadList
                  }
                  if (n.gz && !n.hw) {
                    if (m.hz === n.gz) m.uploadList = n.uploadList
                  }
                })
              })
              imgFlag = notImageArr.some(item => !item.uploadList.length)
            }
            chData.forEach(item => {
              if (item.marketPrice === '' || item.marketPrice === undefined || item.marketPrice === null) {
                marketFlag = true
                return
              }
              if (item.sale === '' || item.sale === undefined || item.sale === null) {
                saleFlag = true
                return
              }
              if (item.code === '' || item.code === undefined || item.code === null) {
                codeFlag = true
                return
              }
            })
            if (imgFlag) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '销售属性里请上传图片'
              })
              return
            }
            if (marketFlag) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '销售属性里请输入建议零售价'
              })
              return
            }
            if (saleFlag) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '销售属性里请输入基础批发价'
              })
              return
            }
            if (codeFlag) {
              this.btnDisable = false
              this.$Notice.error({
                title: '错误提醒',
                desc: '销售属性里请输入SKU编码'
              })
              return
            }
          }

          if (this.$refs.decEdit.tinymceHtml === '') {
            this.btnDisable = false
            this.$Notice.error({
              title: '错误提醒',
              desc: '请填写图文信息'
            })
            return
          }
          this.btnDisable = true
          //商品基本信息
          let productInfoDTO = JSON.parse(JSON.stringify(this.$refs.baseEdit.form))
          delete productInfoDTO.orderNum
          delete productInfoDTO.primaryNum
          productInfoDTO.categoryId = this.isProduct ? this.categoryId : this.secondData.endId
          productInfoDTO.categoryName = this.categoryName
          productInfoDTO.centerProductId = this.centerProductId
          productInfoDTO.productType = this.productType
          if (this.isProduct) productInfoDTO.isShelf = this.$refs.tagEdit.isShelf
          if (!this.productId) productInfoDTO.platform = 'SUPPLIER' // 新增时写死,编辑时不传
          if (this.productId) productInfoDTO.productId = this.productId

          //商品属性
          let productAttributeDTOs = this.productAttributeDTOs.length ? this.$refs.natureEdit.allAttributeArr : []
          if (this.productId) {
            productAttributeDTOs.forEach(item => {
              item.productId = this.productId
            })
          }
          //商品图片
          let uploadPic = this.$refs.picEdit.uploadList
          let idsArr = this.$refs.picEdit.idsArr
          let productInfoImagesDTOs = []
          productInfoImagesDTOs = uploadPic.map((item, n) => {
            let target = {}
            target.sort = item.sort
            target.resource = item.imgUrl
            if (idsArr[n]) target.id = idsArr[n]
            return target
          })
          if (this.productId) {
            productInfoImagesDTOs.forEach(item => {
              item.productId = this.productId
            })
          }

          let productInfoExtDTO = {} //图文描述
          productInfoExtDTO.primaryNum = this.$refs.baseEdit.form.primaryNum // 一手数量
          productInfoExtDTO.orderNum = this.$refs.baseEdit.form.orderNum // 起订数量
          productInfoExtDTO.freightTemplateId = this.$refs.freightEdit.freightTemplateId // 起订数量
          // productInfoExtDTO.description = this.$refs.decEdit.toBackContent;  //商品描述
          let tinymceHtml = this.$refs.decEdit.tinymceHtml
          // let reg=/\http:\/\/zc-peppa-dev.oss-cn-hangzhou.aliyuncs.com/g;
          // let reg = new RegExp(this.preFixPath, 'g')
          // productInfoExtDTO.description = tinymceHtml.replace(reg, '')
          productInfoExtDTO.description = tinymceHtml
          if (this.productId) {
            productInfoExtDTO.productId = this.productId
            productInfoExtDTO.id = this.$refs.decEdit.id
          }
          let productInfoTireExtDTO = {} // 轮胎的属性
          if (this.productType !== 'NORMAL') {
            productInfoTireExtDTO = this.$refs.natureEdit.productInfoTireExtDTO
          }
          if (this.productId) productInfoTireExtDTO.productId = this.productId
          //销售属性（productType == 'NORMAL'）
          let productSkuAttrImagesDTOs = [] // 销售属性的图片
          if (this.productType === 'NORMAL') {
            let tableData = this.$refs.saleEdit.tableData
            let oldSkuAttrImagesDTOs = []
            tableData.forEach((item, n) => {
              let target = {}
              if (item.hw) {
                target.skuAttrNameId = item.hwParentId
                target.skuAttrValueId = item.hw
              } else {
                target.skuAttrNameId = item.gzParentId
                target.skuAttrValueId = item.gz
              }
              target.image = item.uploadList.length && item.uploadList[0].imgUrl
              oldSkuAttrImagesDTOs.push(target)
            })
            for (var i = 0; i < oldSkuAttrImagesDTOs.length; i++) {
              let flag = true
              for (var j = 0; j < productSkuAttrImagesDTOs.length; j++) {
                if (oldSkuAttrImagesDTOs[i].skuAttrValueId === productSkuAttrImagesDTOs[j].skuAttrValueId) {
                  flag = false
                }
              }
              if (flag) {
                productSkuAttrImagesDTOs.push(oldSkuAttrImagesDTOs[i])
              }
            }
            productSkuAttrImagesDTOs.forEach((item, n) => {
              if (this.saleImgIdArr[n]) item.id = this.saleImgIdArr[n]
            })
            if (this.productId) {
              productSkuAttrImagesDTOs.forEach(item => {
                item.productId = this.productId
              })
            }
          }
          //销售属性的其他数据
          let productSkuDTOs = []
          if (this.productType === 'NORMAL') {
            let tableData = this.$refs.saleEdit.tableData
            tableData.forEach((item, n) => {
              let target = {}
              target.barcode = item.proCode
              target.code = item.code
              target.invoicePrice = item.invoice
              target.salePrice = item.sale
              target.marketPrice = item.marketPrice
              if (this.saleSkuIdArr[n]) target.id = this.saleSkuIdArr[n]
              // sku主图start
              let skuIdCount = 0
              if (item.skuImgArr.length) {
                target.productSkuImagesDTOs = [{
                  resource: item.skuImgArr[0].imgUrl,
                  sort: 0
                }]
                if (this.skuMainImgIdArr[skuIdCount]) target.productSkuImagesDTOs[0].id = this.skuMainImgIdArr[n]
                skuIdCount++
              } else {
                target.productSkuImagesDTOs = []
              }
              // sku主图end
              target.stock = item.stock
              target.productSkuAttrDTOs = []
              if (item.hw) {
                let targetHw = {}
                targetHw.attributeName = item.hwParentName
                targetHw.attributeNameId = item.hwParentId
                targetHw.attributeValue = item.hwName
                targetHw.attributeValueId = item.hw
                target.productSkuAttrDTOs.push(targetHw)
              }
              if (item.gz) {
                let targetGz = {}
                targetGz.attributeName = item.gzParentName
                targetGz.attributeNameId = item.gzParentId
                targetGz.attributeValue = item.gzName
                targetGz.attributeValueId = item.gz
                target.productSkuAttrDTOs.push(targetGz)
              }
              productSkuDTOs.push(target)
            })
          } else {
            let skuObj = {}
            skuObj.barcode = productInfoDTO.barcode
            skuObj.code = productInfoDTO.code
            skuObj.invoicePrice = productInfoDTO.invoicePrice
            skuObj.marketPrice = productInfoDTO.marketPrice
            skuObj.salePrice = productInfoDTO.salePrice
            skuObj.stock = productInfoDTO.stock
            // sku主图 start
            // 只有盘古平台的处理是 轮胎商品的时候，新增时productSkuImagesDTOs传[],编辑时传后台传过来的东西,其他平台的处理都是不管新增还是编辑，productSkuImagesDTOs都是传后台传过来的数据
            skuObj.productSkuImagesDTOs = this.productSkuImagesDTOs
            // sku主图 end
            productSkuDTOs.push(skuObj)
          }
          if (this.productId && this.productType !== 'NORMAL') {
            productSkuDTOs[0].id = this.$refs.baseEdit.form.skuId
            productSkuDTOs[0].productId = this.productId
          }

          //商品标签productTagDTOs
          let productTagDTOs = []
          if (this.isProduct) {
            productTagDTOs = this.$refs.tagEdit.productTagDTOs
            if (this.productId) productTagDTOs.forEach(item => item.productId = this.productId)
          }

          // 服务标签productServiceTagIds
          let productServiceTagIds = []
          if (this.isProduct) {
            productServiceTagIds = this.$refs.serverEdit.checkedArr
          }

          let param = {}
          //商品基本信息
          param.productInfoDTO = productInfoDTO
          //商品属性
          param.productAttributeDTOs = productAttributeDTOs
          param.productInfoImagesDTOs = productInfoImagesDTOs //商品图片
          param.productInfoExtDTO = productInfoExtDTO // 图文描述
          if (this.productType !== 'NORMAL') param.productInfoTireExtDTO = productInfoTireExtDTO // 轮胎属性
          if (productSkuAttrImagesDTOs.length > 0 && this.productType === 'NORMAL') param.productSkuAttrImagesDTOs = productSkuAttrImagesDTOs // 销售属性的图片 如果isImage是false的话就不用传
          param.productSkuDTOs = productSkuDTOs
          if (this.isProduct) param.productTagDTOs = productTagDTOs //商品标签
          if (this.isProduct) param.productServiceTagIds = productServiceTagIds //服务标签
          let url = ''
          if (this.isEdit || this.$route.query.from === 'add') {
            url = this.isEdit ? '/product/apply/update' : '/product/apply/submit'
            if (this.isEdit) {
              param.productAuditDTO = JSON.parse(window.sessionStorage.getItem('productAuditDTO'))
            } else {
              param.productAuditDTO = {}
            }
          } else {
            url = this.productId ? '/product/business/update' : '/product/business/save'
          }
          this.$jsonPost(url, param).then(data => {
            if (this.isEdit || Object.keys(this.secondData).length) {
              this.$Notice.success({
                title: '商品申请成功'
              })
              this.$router.replace('/product/apply/list')
            } else {
              let text = this.productId ? '编辑' : '新增'
              this.$Notice.success({
                title: `${text}成功`
              })
              this.$router.replace('/product/manage/list')
            }
            if (window.sessionStorage.getItem('productAuditDTO')) window.sessionStorage.removeItem('productAuditDTO')
          }).catch(() => {
            this.btnDisable = false
          })
        } else {
          this.btnDisable = false
          this.$Notice.error({
            title: '错误提醒',
            desc: '请先完善商品基本信息必填项'
          })
        }
      })
    },
    getTireData () {
      getTireArr().then(data => {
        this.tire_ratioArr = data.data.aspect_ratio.filter(item => item.val).map(item => { //扁平率
          return {
            value: item.val,
            text: item.val ? item.name : ''
          }
        })
        this.tire_sizeArr = data.data.tire_rim.filter(item => item.val).map(item => { //尺寸
          return {
            value: item.val,
            text: item.name
          }
        })
        this.tire_widthArr = data.data.width.filter(item => item.val).map(item => { //胎面宽
          return {
            value: item.val,
            text: item.name
          }
        })
      })
    },
    changeCategory () {
      this.$Modal.confirm({
        title: '确认',
        content: `确认要切换类目吗？切换类目后将本页数据将全部被清空！`,
        onOk: () => {
          this.$router.push({
            name: 'product/apply/add',
            from: this.isEdit ? 'edit' : 'add',
            productId: this.isEdit ? this.productId : null
          })
        }
      })
    },
    changeFigureData (data) {
      if (data) {
        this.$refs.picEdit.uploadList = data.figureTemplateImagesDTOS.map(item => {
          return {
            sort: item.sort,
            imgUrl: item.resource,
            status: 'finished'
          }
        })
        this.$refs.decEdit.tinymceHtml = data.imageExtInfo // 有可能图片的链接地址是外网的
      }
    },
    onBrandFigure (val) { // 品牌改变之后，类目属性里的花纹要清空
      let natureEdit = this.$refs.natureEdit
      natureEdit.productInfoTireExtDTO.tireFigure = null
      natureEdit.brandId = val
      natureEdit.productAttributeDTOs.forEach(item => {
        if (item.name === '花纹' && item.attributeValueId) {
          item.attributeValueId = null
        }
      })
    }
  }
}
</script>
